package com.zyl.pts.web.inteceptor;
import com.zyl.pts.domain.bean.Account;
import com.zyl.pts.mapper.UserMapper;
import com.zyl.pts.utils.CUtil;
import com.zyl.pts.utils.JwtUtil;
import com.zyl.pts.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**1
 * @version v1.0
 * @ProjectName: product_source
 * @Package: com.zyl.pts.web.interceptor
 * @ClassName: AuthInterceptor
 * @Description TODO(认证拦截器)
 * @Author 翟玉龙
 * @Date 2024/11/19-11:50
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private final UserMapper userMapper;

    public AuthInterceptor(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 在请求被真正执行之前，完成登录认证的工作
     * @param request  请求对象
     * @param response 响应对象
     * @return 认证的结果
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的方式
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            // OPTIONS请求为 跨域时发送的预请求，无需拦截
            return true;
        }
        // 获取请求头中携带的token信息
        String token = request.getHeader("token");

        // 校验token
        String username = JwtUtil.getValue(token, "userName", String.class);
        String userId = JwtUtil.getValue(token, "userId", String.class);
        CUtil.logInfo("当前登录的用户为: " + username);

        Account user = userMapper.getUserById(userId);
        ThreadLocalUtil.set(user);


        // 校验通过
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}